const express = require('express')
const router = express.Router()
const humps = require('humps')
const db = require('../../database/db')
const upload = require('../../utils/img_upload')

module.exports = (() => {
    // 市场管理
    router.get('/archives', async (req, res, next) => {
        try {
            let sql = ''
            req.query.from ? sql += 'AND a.`insurance_time` >= "' + req.query.from + '" AND a.`insurance_time` <= "' + req.query.to + '" ' : ''
            const doc = humps.camelizeKeys(await db.getArchives({ limit: req.query.limit, offset: req.query.offset, search: req.query.search, sql }))
            const temp = []
            const promises = []
            doc.forEach(item => {
                const promise = new Promise(async resolve => {
                    const warrantMan = (item.warrantManId && await db.getWarrantManById(item.warrantManId))
                    item.warrantMan = warrantMan ? warrantMan.name : ''
                    const loanCompany = item.loanCompanyId && await db.getTrialById(item.loanCompanyId)
                    item.loanCompany = loanCompany ? loanCompany.name : ''
                    temp.push(item)
                    resolve(temp)
                })
                promises.push(promise)
            })
            Promise.all(promises).then(async () => {
                const { total } = await db.getArchivesTotal({ search: req.query.search, sql })
                res.send({
                    doc,
                    total
                })
            })
        } catch (err) {
            next(err)
        }
    })

    router.post('/editArchive/', upload, async (req, res, next) => {
        try {
            const form = JSON.parse(req.body.form)
            let existArchive = await db.getArchiveById(form.id)
            if (!existArchive) {
                res.json({
                    status: 0,
                    msg: '该条不存在！'
                })
                return
            }
            const promotion = form.promotionName && await db.getPromotionByName(form.promotionName)
            const distribution = form.distributionName && await db.getDistributionByName(form.distributionName)
            const center = form.center && await db.getCenterByName(form.center)
            const dept = form.dept && await db.getDeptByName({ name: form.dept, center: form.center })
            const salesman = form.salesman && await db.getSalesmanByName({ name: form.salesman, dept: form.dept, center: form.center })
            const warrantMan = form.warrantMan && await db.getWarrantManByName(form.warrantMan)
            const loanCompany = form.loanCompany && await db.getTrialByName(form.loanCompany)
            console.log(form)
            const data = {
                id: form.id,
                number: form.number,
                complete_time: form.complateTime ? form.complateTime : '',
                sign_time: form.signTime ? form.signTime : '',
                name: form.name,
                id_card: form.idCard,
                phone: form.phone,
                phone1: form.phone1,
                phone2: form.phone2,
                promotion_id: promotion ? promotion.id : 0,
                distribution_id: distribution ? distribution.id : 0,
                home_address: form.homeAddress,
                register_address: form.registerAddress,
                use_area: form.useArea,
                license_plate_number: form.licensePlateNumber,
                center_id: center ? center.id : 0,
                dept_id: dept ? dept.id : 0,
                salesman_id: salesman ? salesman.id : 0,
                cartype: form.cartype,
                warrant_man_id: warrantMan ? warrantMan.id : 0,
                frame_number: form.frameNumber,
                guidance_price: form.guidancePrice,
                insurance_time: form.insuranceTime ? form.insuranceTime : '',
                insurance_company: form.insuranceCompany,
                loan_company_id: loanCompany ? loanCompany.id : 0,
                installment: form.installment,
                installment_time: form.installmentTime ? form.installmentTime : '',
                loan_amount: form.loanAmount,
                loan_period: form.loanPeriod,
                delivery_voucher: req.files[0] ? req.files[0].filename : form.deliveryVoucher,
                delivery_photo: req.files[1] ? req.files[1].filename : form.deliveryPhoto,
                remarks: form.remarks,
            }
            const success = await db.updateArchive(data)

            if (success) {
                res.json({
                    status: 1,
                    msg: 'ok'
                })
            }
        } catch (err) {
            next(err)
        }
    })

    router.delete('/removeArchive/:id', async (req, res, next) => {
        try {
            let existArchive = await db.getArchiveById(req.params.id)
            if (!existArchive) {
                res.json({
                    status: 0,
                    msg: '该条不存在！'
                })
                return
            }

            const success = await db.rmArchiveById(req.params.id)

            if (success) {
                res.json({
                    status: 1,
                    msg: 'ok'
                })
            }
        } catch (err) {
            next(err)
        }
    })

    return router
})();